<?php
//Session保存路径
$sessSavePath = "../sessions/";
if(is_writeable($sessSavePath) && is_readable($sessSavePath)){ session_save_path($sessSavePath); }

session_start();

//获取随机字符
$rndstring = '';
for($i=0; $i<4; $i++) $rndstring .= chr(mt_rand(65,90));

//如果支持GD，则绘图
if(function_exists("imagecreate"))
{
	//Firefox部份情况会多次请求的问题，5秒内刷新页面将不改变session
	$ntime = time();
	if(empty($_SESSION['checkcode_last']) || empty($_SESSION['checkcode_ico']) || ($ntime - $_SESSION['checkcode_last'] > 5))
	{
		$_SESSION['checkcode_ico'] = strtolower($rndstring);
		$_SESSION['checkcode_last'] = $ntime;
	}
	$rndstring = $_SESSION['checkcode_ico'];
	$rndcodelen = strlen($rndstring);

	//创建图片，并设置背景色
	$im = imagecreate(80,30);
	ImageColorAllocate($im, mt_rand(12,60),mt_rand(25,150),mt_rand(100,250));

	//背景线
	$lineColor1 = ImageColorAllocate($im,mt_rand(0,80),mt_rand(0,40),mt_rand(0,155));
	$lineColor2 = ImageColorAllocate($im,mt_rand(30,255),mt_rand(50,255),mt_rand(30,255));
	for($j=3;$j<=20;$j=$j+3)
	{
		imageline($im,2,mt_rand(2,28),78,mt_rand(2,78),$lineColor1);
	}
	for($j=2;$j<250;$j++)
	{
		imagesetpixel($im,mt_rand()%80,mt_rand()%30,$lineColor2);
	}

	//画边框
	$bordercolor = ImageColorAllocate($im, 87,34,9);
	imagerectangle($im, 0, 0, 79, 29, $bordercolor);

	//输出文字
	$fontColor = ImageColorAllocate($im, 255,255,255);
	for($i=0;$i<$rndcodelen;$i++)
	{
		$bc = mt_rand(0,1);
		$rndstring[$i] = strtoupper($rndstring[$i]);
		//imagestring($im, mt_rand(3,6), $i*16+12, mt_rand(2,15), $rndstring[$i], $fontColor);
		imagettftext($im, 15, mt_rand(-8,18), $i*18+6,mt_rand(20,25) , $fontColor, '../common/data/fzjz.ttf', $rndstring[$i]);


	}

	header("Pragma:no-cache\r\n");
	header("Cache-Control:no-cache\r\n");
	header("Expires:0\r\n");

	//输出特定类型的图片格式，优先级为 gif -> jpg ->png
	if(function_exists("imagejpeg"))
	{
		header("content-type:image/jpeg\r\n");
		imagejpeg($im);
	}
	else
	{
		header("content-type:image/png\r\n");
		imagepng($im);
	}
	ImageDestroy($im);
	exit();
}
else
{
	//不支持GD，只输出字母 ABCD
	$_SESSION['checkcode_ico'] = "abcd";
	$_SESSION['dd_ckstr_last'] = '';
	header("content-type:image/jpeg\r\n");
	header("Pragma:no-cache\r\n");
	header("Cache-Control:no-cache\r\n");
	header("Expires:0\r\n");
	$fp = fopen("data/vdcode.jpg","r");
	echo fread($fp,filesize("data/vdcode.jpg"));
	fclose($fp);
	exit();
}

?>